using System;
using System.Collections;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Design;
using Microsoft.VisualStudio.Shell.Interop;

namespace VSSDKAssist.Platform.Helpers
{
	public class TypeDiscoveryHelper
	{
		#region Fields
		private IServiceProvider provider;
		#endregion

		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="TypeDiscoveryHelper"/> class.
		/// </summary>
		/// <param name="provider">The provider.</param>
		public TypeDiscoveryHelper(IServiceProvider provider)
		{
			this.provider = provider;
		}
		#endregion

		#region Public Implementation
		/// <summary>
		/// Gets the types on project and its references.
		/// </summary>
		/// <param name="baseType">The base type to filter on.</param>
		/// <returns>List of types</returns>
		public ICollection GetTypes(Type baseType)
		{
			DynamicTypeService typeService = provider.GetService(typeof(DynamicTypeService)) as DynamicTypeService;
			
			IVsHierarchy vsHierarchy = GetCurrentSelection(provider);

			ITypeDiscoveryService discovery = typeService.GetTypeDiscoveryService(vsHierarchy);

			return discovery.GetTypes(baseType, false);
		}
		#endregion

		#region Private Implementation
		private static IVsHierarchy GetCurrentSelection(IServiceProvider provider)
		{
			IVsMonitorSelection selection = (IVsMonitorSelection)provider.GetService(typeof(SVsShellMonitorSelection));
			IntPtr ptr1 = IntPtr.Zero;

			IVsMultiItemSelect vsMultiItemSelect = null;
			IntPtr ptr2 = IntPtr.Zero;

			uint pitemid;
			selection.GetCurrentSelection(out ptr1, out pitemid, out vsMultiItemSelect, out ptr2);
			if(ptr1 != IntPtr.Zero)
			{
				return (IVsHierarchy)Marshal.GetObjectForIUnknown(ptr1);
			}
			IVsHierarchy vsHierarchy = (IVsHierarchy)provider.GetService(typeof(SVsSolution));
			return vsHierarchy;
		}
		#endregion
	}
}
